<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.resourceType" class="filter-item" placeholder="资源类型" :clearable="true">
        <el-option value="0" label="图片" />
        <el-option value="1" label="视频" />
        <el-option value="2" label="其他" />
      </el-select>
      <el-select v-model="listQuery.resourceStatus" class="filter-item" placeholder="资源状态" :clearable="true">
        <el-option value="0" label="正常" />
        <el-option value="1" label="停用" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="序号" align="center" width="100">
        <template slot-scope="{$index}">
          <span>{{ $index+1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="资源名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.resourceName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="资源类型" align="center" width="100">
        <template slot-scope="{row}">
          <span>{{ row.resourceType }}</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="{row}">
          <span>{{ row.resourceStatus==='0'?'公开':'关闭' }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column label="上传人">-->
      <!--<template slot-scope="{row}">-->
      <!--<span>{{ row.userType }}</span>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row,$index)">
            修改
          </el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(row,$index)">
            预览
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="400px">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="70px" style="width: 100%;margin:0 auto">

        <el-row v-show="dialogStatus==='create'">
          <el-col>
            <el-form-item label="获取资源" prop="title">
              <el-upload
                class="upload-demo"
                action="http://106.54.201.206:11000/api/resource/upload"
                :data="{module:'resource'}"
                :headers="fileHeader"
                name="fileName"
                :on-success="handleFileSuccess"
                :file-list="fileList"
                :limit="1"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
              </el-upload>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="资源名称" prop="title">
              <el-input v-model="temp.resourceName" />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="资源类型" prop="type">
              <el-input v-model="temp.resourceType" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="资源状态" prop="type">
              <el-select v-model="temp.resourceStatus" class="filter-item" placeholder="请选择">
                <el-option value="0" label="正常" />
                <el-option value="1" label="停用" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pageQuareApi, editApi, getByIdApi, addApi, DeleteApi } from '@/api/sysmanage'
import { getTypeList, getAllOrgList } from '@/api/public'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getToken } from '@/utils/auth'
export default {
  name: 'ComplexTable',
  components: { Pagination },

  directives: { waves },
  data() {
    return {
      /* eslint-disable */
        value:'',
        getTypeList:[],
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          "limit": 10,
          "page": 1,
          "resourceStatus": "",
          "resourceType": ""
        },
        temp:  {
          "id": '',
          "resourceName": "",
          "resourceStatus": "1",
          "resourceType": ""
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '新增'
        },
        rules: {
          type: [{ required: true, message: 'type is required', trigger: 'change' }],
          timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
          title: [{ required: true, message: 'title is required', trigger: 'blur' }]
        },
        downloadLoading: false,
        updateObj:{
          index:'',
          data:[]
        },
        fileHeader:'',
        fileList:[]
      }
    },
    created() {
      this.getList()
      this.getTypeList=getTypeList()
      let token=getToken('Admin-Token')
      this.fileHeader={
        token:token
      }
    },
    methods: {
      dropzoneS(file) {
        console.log('TCL: dropzoneS -> dropzoneS', file)
        this.$message({ message: 'Upload success', type: 'success' })
      },
      dropzoneR(file) {
        console.log(file)
        this.$message({ message: 'Delete success', type: 'success' })
      },
      getList() {
        this.listLoading = true
        pageQuareApi (this.listQuery,'resource').then(response => {
          this.list = response.data.list
          this.total = response.data.total
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      resetTemp() {//重置修改模态框
        this.fileList=[]
        this.temp = {
         	"id": '',
          "resourceName": "",
          "resourceStatus": "1",
          "resourceType": ""
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid=true) {
            addApi(this.temp,'resource').then((res) => {
              if(res.code==='200'){
                this.$message({
                  message: res.message,
                  type: 'success',
                })
                this.dialogFormVisible = false
                this.list.unshift(res.data)
                //  this.handleFilter()//刷新重新请求
              }
            })
          }
        })
      },
      handleUpdate(row,index) {
        this.resetTemp()
        getByIdApi({id:row.id},'resource').then(res=>{
        console.log("TCL: handleUpdate -> res", res)
          const {data}=res
          this.temp={
            "id":data.id,
            "resourceName":data.resourceName,
            "resourceStatus": data.resourceStatus,
            "resourceType":  data.resourceType,
          }
        }).catch()
        //保存修改的行数据，索引
        this.updateObj={
          index:index,
          data:row
        }
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid=true) {
            
            // tempData.id=this.updateObj.data.id//获取修改ID
            editApi(this.temp,'resource').then((res) => {
              this.dialogFormVisible = false
              if(res.code==='200'){
                this.$message({
                  message: res.message,
                  type: 'success',
                })
                const {index,data}=this.updateObj
                const row=Object.assign(data, this.temp)
                console.log("TCL: updateData -> row", row)
                this.list.splice(index,1,row)
              }else{
                this.$message({
                  message: res.message||'修改失败',
                  type: 'error'
                })
              }

            })
          }
        })
      },
      handleDelete(row,index) {
        this.$confirm('此操作不可逆, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }).then(res => {
          DeleteApi({id:row.id},'resource').then(res=>{
            this.$message({
              message: res.message,
              type: 'success'
            })
            this.list.splice(index,1)
          }).catch(err=>{
            this.$message({
              message:err.message,
              type: 'error'
            })
          })

          // row.status = status
        })
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
          const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
          const data = this.formatJson(filterVal, this.list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'table-list'
          })
          this.downloadLoading = false
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      },
      handleFileSuccess(response, file, fileList){
        console.log("TCL: handleFileSuccess -> response", response)
        this.fileList=fileList
        const {data}=response
         this.temp.id=data.id
          this.temp.resourceName=data.originalName
           this.temp.resourceType=data.fileType
        console.log("TCL: handleFileSuccess ->  this.temp",  this.temp)
      },

    }
  }
</script>
